package com.xingtu.testSerialport

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.cmcc.sy.hap.sdk.ICallback
import com.cmcc.sy.hap.sdk.JniLib
import com.xingtu.testSerialport.adapter.TextListAdapter
import com.xingtu.testSerialport.entity.BoardCardS6
import com.xingtu.testSerialport.entity.GPSData
import com.xingtu.testSerialport.utils.CommonFunction
import com.xingtu.testSerialport.utils.SerialPortUtils
import kotlinx.android.synthetic.main.activity_main.*
import tp.xmaihh.serialport.SerialHelper
import tp.xmaihh.serialport.bean.ComBean
import tp.xmaihh.serialport.stick.AbsStickPackageHelper
import tp.xmaihh.serialport.utils.ByteUtil
import java.io.IOException
import java.nio.charset.StandardCharsets


class MainActivity : AppCompatActivity() {


    private var serialHelper2: SerialHelper? = null  //S2板卡
    private var serialHelper6: SerialHelper? = null //测试板卡
    private var serialHelper4: SerialHelper? = null //电台(发送移动差分信息)
    private var isHexType = false
    private var text = ""
    //    var chafenThread:Thread?=null

    private val mHandler = Handler { msg ->
        when (msg.what) {
            -1 -> {
                ToastUtils.showLong("关闭串口")
            }
            1 -> { //S2板卡返回
                var data = msg.obj as GPSData
                info_tv5_.text = "卫星数量:${data.satelliteNumber}"
                info_tv8.text = "差分期age:${data.age}"
                info_tv7.text = "状态位:${data.solutionType}"
                //                LogUtils.e("age=${data.age}   solutionType=${data.solutionType}")
                //                if (data.solutionType==4 && data.age<6){
                //                    info_tv9.text = "解状态:固定解"
                //                }else{
                //                }
                info_tv9.text = "解状态:${CommonFunction.getStats(data.solutionType)}"
                info_tv10.text = "航向角:${data.heading}"

                //                listAdapter.addData(text)
                //                if (ObjectUtils.isNotEmpty(listAdapter)) {
                //                    recyclerView.smoothScrollToPosition(listAdapter.data.size)
                //                }
            }
            2 -> {
                //S6板卡返回
                LogUtils.e("s6展示数据")
                val data = msg.obj as BoardCardS6
                info_tv1.text = "横滚角:${data.rollAngle}"
                info_tv2.text = "俯仰角:${data.pitchAngle}"
                info_tv3.text = "航向角:${data.courseAngle}"
                info_tv4.text = "RTK定位状态:${RTKStauts[data.RTKStatus]}"
                info_tv5.text = "卫星数量:${data.satellites}"
                info_tv6.text = "差分延迟:${data.differentialDelay}"
            }
        }


        false
    }

    lateinit var context: Context
    lateinit var listAdapter: TextListAdapter
    var strList = ArrayList<String>()

    var gpsData = GPSData()
    var boardCardS6 = BoardCardS6()

    /**
     * 1输出0不输出；
     */
    var isExport = 0
    private lateinit var RTKStauts: Array<String> //

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context = this
        RTKStauts = context.resources.getStringArray(R.array.RTK_Status)
        //        recyclerView.layoutManager = LinearLayoutManager(context)
        //        listAdapter = TextListAdapter(strList)
        //        recyclerView.adapter = listAdapter


        //初始化串口
        initSerialPort6()
        initSerialPort4()
        initSerialConfig()
        //初始化设置中国移动时间池
        initCmccTimePool()
        //初始化信息要在open之间进行
        switch_checkbox.setOnCheckedChangeListener { compoundButton, b ->
            if (ObjectUtils.isNotEmpty(serialHelper2)) {
                if (b) { //开
                    if (serialHelper2!!.isOpen == true) {
                        Toast.makeText(this, "串口已经打开", Toast.LENGTH_SHORT).show()
                        return@setOnCheckedChangeListener
                    }
                    openSerial(true)
                } else {
                    //关
                    if (serialHelper2!!.isOpen == true) {
                        Toast.makeText(this, "关闭串口", Toast.LENGTH_SHORT).show()
                        openSerial(false)
                    } else {
                        Toast.makeText(this, "串口已经关闭", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        switch_export_cb.setOnCheckedChangeListener { compoundButton, b ->
            //TODO 是否输出
            isExport = if (b) 1 else 0
        }
        //TODO 打开串口
        openSerial(true)
    }

    //<editor-fold desc="打开串口">
    fun openSerial(isOpen: Boolean) {
        if (isOpen) {
            if (serialHelper6 != null && ObjectUtils.isNotEmpty(serialHelper6)) {
                serialHelper6?.open()
            }
            if (ObjectUtils.isNotEmpty(serialHelper4)) {
                serialHelper4?.open()
            }
            if (ObjectUtils.isNotEmpty(serialHelper2)) {
                openInit()
                serialHelper2?.open()

            }
            JniLib.startSdk(callback)
        } else {
            JniLib.stopSdk()
            if (ObjectUtils.isNotEmpty(serialHelper6)) {
                serialHelper6?.close()
            }
            if (ObjectUtils.isNotEmpty(serialHelper4)) {
                serialHelper4?.close()
            }
            if (ObjectUtils.isNotEmpty(serialHelper2)) {
                serialHelper2?.close()
            }
            serialHelper2 = null
            serialHelper6 = null
            serialHelper4 = null
        }
    }
    //</editor-fold>


    //<editor-fold desc="ttyS2-初始化串口">
    var gpggaStr = ""
    var headStr = ""
    fun initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率（此处为接收扫码数据）
        serialHelper2 = object : SerialHelper("/dev/ttyS2", 115200) {
            override fun onDataReceived(paramComBean: ComBean) {
                val message = mHandler.obtainMessage()

                //                LogUtils.json(LogUtils.E, message.obj)
                var rxText: String
                rxText = String(paramComBean.bRec, StandardCharsets.UTF_8)
                //
                //                if (isHexType) {
                //                    //转成十六进制数据
                //                    rxText = ByteUtil.ByteArrToHex(paramComBean.bRec)
                //                }
                if ((rxText.startsWith("${'$'}GPGGA,") || rxText.startsWith("${'$'}GNGGA,")) && rxText.contains("${'$'}GPRMC,") && rxText.contains("#HEADINGA,")) {

                    var info = rxText.split("\r\n").subList(0, 3)
                    for (i in info.indices) {
                        when (i) {
                            0 -> {
                                if (SerialPortUtils.CRCCheck(info[0])) { //GPGGA
                                    gpggaStr = info[0]
                                    JniLib.sendGGA(gpggaStr)
                                    gpsData.setData(gpggaStr)
                                    //      $GPGGA,070146.40,4544.42289332,N,12640.19321458,E,4,39,0.4,158.1779,M,14.1808,M,01,238*59
                                    //                                    LogUtils.e(gpggaStr)

                                }
                            }
                            1 -> {
                                //                                LogUtils.e("${info[1]}")
                            }
                            2 -> { //
                                LogUtils.e("${info[2]}")
                                headStr = info[2]
                                //HEADINGA,COM1,0,74.0,FINE,2308,455941.600,13657710,22,18;INSUFFICIENT_OBS,NONE,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,"",0,0,0,0,0,00,0,0*77afd924
                                gpsData.setHeadData(headStr)
                            }
                        }
                    }
                    message.what = 1
                    message.obj = gpsData
                    //                    mHandler.sendMessage(message)
                    mHandler.sendMessageDelayed(message, 1000)
                }
            }
        }

        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper2!!.stickPackageHelper = AbsStickPackageHelper {
            try {
                val available = it.available()
                if (available > 0) {
                    val buffer = ByteArray(available)
                    val size = it.read(buffer)
                    if (size > 0) {
                        return@AbsStickPackageHelper buffer
                    }
                } else {
                    SystemClock.sleep(100)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            null
        }


    }

    //</editor-fold>


    //<editor-fold desc="ttyS6">
    fun initSerialPort6() {
        //初始化SerialHelper对象，设定串口名称和波特率（此处为接收扫码数据）
        serialHelper6 = object : SerialHelper("/dev/ttyS6", 115200) {
            override fun onDataReceived(paramComBean: ComBean) {
                val message = mHandler.obtainMessage()
                var rxText = ""
                //转成十六进制数据
                rxText = ByteUtil.ByteArrToHex(paramComBean.bRec)
                //                var a = "FFA44A1701D3620200791C00009B553200041F0403001DFF"
                if (rxText.startsWith("FFA44A") && rxText.length > 10) {
                    boardCardS6.setData(rxText)
                    when (boardCardS6.code) {
                        SerialPortUtils.rCode1 -> {
                            if (boardCardS6.RTKStatus > 0) {
                                message.what = 2
                                message.obj = boardCardS6
                                mHandler.sendMessageDelayed(message, 1000)
                            }
                        }
                    }

                    //                    mHandler.sendMessage(message)

                }

            }
        }
        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper6!!.stickPackageHelper = AbsStickPackageHelper {
            try {
                                val available = it.available()
//                val available = 28
                //                LogUtils.e("S6=acvailable=${available}")
                if (available > 0) {
                    val buffer = ByteArray(available)
                    val size = it.read(buffer)
                    if (size > 0) {
                        return@AbsStickPackageHelper buffer
                    }
                } else {
                    SystemClock.sleep(100)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            null
        }
    }
    //</editor-fold>

    //<editor-fold desc="ttyS4">
    fun initSerialPort4() {
        //初始化SerialHelper对象，设定串口名称和波特率（此处为接收扫码数据）
        serialHelper4 = object : SerialHelper("/dev/ttyS4", 115200) {
            override fun onDataReceived(paramComBean: ComBean) {
                var rxText: String
                //                rxText = String(paramComBean.bRec, StandardCharsets.UTF_8)

                //                if (isHexType) {
                //                    //转成十六进制数据
                //
                //                }
                rxText = ByteUtil.ByteArrToHex(paramComBean.bRec)


            }
        }

        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper4!!.stickPackageHelper = AbsStickPackageHelper {
            try {
                val available = 24
                if (available > 0) {
                    val buffer = ByteArray(available)
                    val size = it.read(buffer)
                    if (size > 0) {
                        return@AbsStickPackageHelper buffer
                    }
                } else {
                    SystemClock.sleep(100)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            null
        }
    }
    //</editor-fold>

    //<editor-fold desc="中国移动时间池差分">
    lateinit var callback: ICallback
    fun initCmccTimePool() {
        var name = "sjcjvvq3899"
        var password = "xt20dh31"
        var deviceId = MyApplication.getDeviceUniqID(MyApplication.getInstance())
        JniLib.setTimeUserInfo(name, password, deviceId)
        callback = object : ICallback {
            override fun rtcmConsumer(bytes: ByteArray?, p1: Int?, p2: Int?) {
                //                LogUtils.e("bytes=${bytes?.size}   p2=${p2}")
                if (p2 == 2001) {
                    //发送
                    if (ObjectUtils.isNotEmpty(serialHelper2) && serialHelper2?.isOpen == true) {
                        serialHelper2?.send(bytes)
                    }
                    if (ObjectUtils.isNotEmpty(serialHelper4) && serialHelper4?.isOpen == true) {
                        serialHelper4?.send(bytes)
                        LogUtils.e("差分=发送S4")
                    }
                }
                try {
                    Thread.sleep(1000)
                } catch (e: Exception) {

                }
            }
        }
        //        LogUtils.e("RtcmStatus=${JniLib.getRtcmStatus()}")

    }
    //</editor-fold>


    //<editor-fold desc="初始化板卡设置返回数据信息格式">
    var cmd = ""
    fun openInit() {
        try {
            if (ObjectUtils.isNotEmpty(serialHelper2) && serialHelper2!!.isOpen) {
                LogUtils.e("串口已打开")
                //TODO 给串口发数据才能 返回精确的数据
                cmd = "com,com1,115200\r\n"
                var bytes = cmd.toByteArray()
                serialHelper2?.baudRate = 115200
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.baudRate = 57600
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.baudRate = 38400
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)


                cmd = "com,com1,115200\r\n"
                serialHelper2?.baudRate = (19200)
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                serialHelper2?.baudRate = (9600)
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                serialHelper2?.baudRate = (115200)
                cmd = "saveconfig\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)

                cmd = "unlog\r\n"
                serialHelper2?.sendTxt(cmd)
                bytes = cmd.toByteArray()
                Thread.sleep(100)

                cmd = "CONFIG NMEA0183 V41\r\n"
                serialHelper2?.baudRate = (115200)
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "GPGGA com1 0.1\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "GPRMC com1 0.1\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "HeadingA com1 0.1\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)
                //                cmd = "GPZDA com1  10\r\n"
                //                LogUtils.e(cmd, bytes)
                //                serialHelper?.sendTxt(cmd)
                //                Thread.sleep(100)

                cmd = "saveconfig\r\n"
                bytes = cmd.toByteArray()
                serialHelper2?.sendTxt(cmd)
                Thread.sleep(100)

            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    //</editor-fold>

    fun onclick(view: View) {
        when (view.id) {
            R.id.save_tv1 -> { //
                //                val a = "FFA44A17019268FFFFF2E00100FBCC2F000415000000DF"
                //                val first =SerialPortUtils.getHexB10Int(a)
                //                LogUtils.e("first="+first)
                //                boardCardS6.setData(a)


                //                info_tv1.text = "横滚角:${boardCardS6.rollAngle}"
                //                info_tv2.text = "俯仰角:${boardCardS6.pitchAngle}"
                //                info_tv3.text = "航向角:${boardCardS6.courseAngle}"
                //                info_tv4.text = "RTK定位状态:${RTKStauts[boardCardS6.RTKStatus]}"
                //                info_tv5.text = "卫星数量:${boardCardS6.satellites}"
                //                info_tv6.text = "差分延迟:${boardCardS6.differentialDelay}"

                if (!serialHelper2!!.isOpen) {
                    Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show()
                    return
                }
                sendMessage(1)
            }
            R.id.save_tv2 -> { //保存2
                if (!serialHelper2!!.isOpen) {
                    Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show()
                    return
                }
                sendMessage(2)
            }
            R.id.save_tv3 -> { //保存3
                if (!serialHelper2!!.isOpen) {
                    Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show()
                    return
                }
                sendMessage(3)
            }

        }
    }

    //<editor-fold desc="发送板卡串口信息">
    fun sendMessage(type: Int) {
        var message = ByteArray(0)
        when (type) {
            1 -> { //0x11杆臂配置信息
                val b1 = SerialPortUtils.int2bytes2(setting1_et1.editableText.toString().toInt())
                val b2 = SerialPortUtils.int2bytes2(setting1_et2.editableText.toString().toInt())
                val b3 = SerialPortUtils.int2bytes2(setting1_et3.editableText.toString().toInt())
                val bytes = SerialPortUtils.byteAppand(b1, b2, b3)
                message = SerialPortUtils.GetMsgBytes(SerialPortUtils.code1, bytes)
                LogUtils.e("bytes=size= ${bytes.size}")
            }
            2 -> { //0x13IMU配置安装旋转角
                val b1 = SerialPortUtils.int2bytes1(setting2_et1.editableText.toString().toInt())
                val b2 = SerialPortUtils.int2bytes1(setting2_et2.editableText.toString().toInt())
                val b3 = SerialPortUtils.int2bytes1(setting2_et3.editableText.toString().toInt())
                val bytes = SerialPortUtils.byteAppand(b1, b2, b3)
                message = SerialPortUtils.GetMsgBytes(SerialPortUtils.code3, bytes)
            }
            3 -> { //0x12IMU信息输出
                val b1 = SerialPortUtils.int2bytes1(isExport)
                val bytes = SerialPortUtils.byteAppand(b1)
                message = SerialPortUtils.GetMsgBytes(SerialPortUtils.code2, bytes)
            }
        }
        serialHelper2!!.send(message)
    }
    //</editor-fold>

    override fun onDestroy() {
        super.onDestroy()
        openSerial(false)
    }
}